"""简单重构simple crawler.
还要优化：多个参数传入  show开放  参数抽象
"""

import re
from urllib import request


class Spider():
    """spider."""

    def __init__(self, url, target, target_name, target_number):
        """初始化"""
        self.url = url
        self.target = target
        self.target_name = target_name
        self.target_number = target_number

    def __get_html(self):
        # 获取html
        r = request.urlopen(self.url)
        html = r.read()
        html = str(html, encoding="utf-8")
        return html

    def __get_target(self, html):
        # 获取目标div
        divs = re.findall(self.target, html)
        targets = []
        for div in divs:
            name = re.findall(self.target_name, div)
            number = re.findall(self.target_number, div)
            # re.findall 返回[]
            target = {'name': name, 'number': number}
            targets.append(target)
        return targets
        # targets[{'name': [name], 'number': [number]}]

    def __clean(self, targets):
        # """
        # 数据清洗
        # target是{}   字典
        # target['name']得到[name]  是数组
        # 数组里只有一个元素  target['name'][0]
        # strip() 用于移除字符串头尾指定的字符（默认为空格或换行符）或字符序列
        # 该方法只能删除开头或是结尾的字符，不能删除中间部分的字符。
        # """
        # def cleaning(target):
        #     name = target['name'][0].strip()
        #     number = target['number'][0].strip()
        #     return {'name': name, 'number': number}

        # return map(cleaning, targets)
        # [{'name': name, 'number': number}]
        return map(
            lambda target: {
                'name': target['name'][0].strip(),
                'number': target['number'][0].strip()
            }, targets)

    def __sort_seed(self, clean):
        if '万' in clean['number']:
            num = re.findall(r'\d*', clean['number'])
            return float(num[0]) * 10000
        num = re.findall(r'\d*', clean['number'])
        return float(num[0])

    def __show(self, cleaned):
        sort = sorted(cleaned, key=self.__sort_seed, reverse=True)
        for rank in range(0, len(sort)):
            print(
                str(rank + 1) + '     ' +
                sort[rank]['name'] + '     ' +
                sort[rank]['number']
            )

    def start(self):
        """enter."""
        html = self.__get_html()
        targets = self.__get_target(html)
        cleaned = self.__clean(targets)
        # print(list(cleaned))
        self.__show(cleaned)
        print('done')

# 网址
url = r'https://www.panda.tv/cate/lol?pdt=1.18.i12.0.53evmf34pcf'

# 目标div
target = r'<div class="video-info">([\d\D]*?)</div>'

# 目标div 里的内容
target_name = r'<span class="video-nickname" title="([\d\D]*?)">'

# 目标div 里的内容
target_number = r'<span class="video-number">([\d\D]*?)</span>'

spider = Spider(url, target, target_name, target_number)
spider.start()
